<?php

namespace App\Utils;

use Route;
use Log;
use DB;
use App\Cache\BaseCache;

class ReturnUtils {

    protected $request = null;
    public $RETURN_LANGUE = 'zh-CN'; //返回
    public $return = array(
        //成功
        'SUCCESS' => array('code' => 0, 'name' => array('en' => 'Success', 'zh-CN' => '成功')),
        //1000 - 1999
        //未知错误（系统错误）
        'ERROR_UNKNOWN' => array('code' => 1000, 'name' => array('en' => 'Unknown error', 'zh-CN' => '未知错误')),
        //IP校验：IP访问频繁被加入黑名单
        'ERROR_LIMIT_IP' => array('code' => 1001, 'name' => array('en' => 'Access restricted', 'zh-CN' => '访问受限')),
        //IP校验：此IP不在白名单内
        'ERROR_IP_WHITE' => array('code' => 1002, 'name' => array('en' => 'Access restricted', 'zh-CN' => '访问受限')),
        //文件类：
        'ERROR_FILE_NOTEXIST' => array('code' => 1010, 'name' => array('en' => "The file couldn't be found", 'zh-CN' => '找不到目标文件')),
        //文件类：
        'ERROR_FILE_PERMISSION' => array('code' => 1011, 'name' => array('en' => 'Insufficient permission', 'zh-CN' => '权限不足')),
        //参数校验失败: 未查明原因
        'ERROR_PARAMETER' => array('code' => 1100, 'name' => array('en' => 'Parameter error', 'zh-CN' => '参数校验失败')),
        //参数校验失败：个数不正确
        'ERROR_PARAMETER_TOTAL' => array('code' => 1101, 'name' => array('en' => 'Parameter error', 'zh-CN' => '参数个数不正确')),
        //参数校验失败：未知参数
        'ERROR_PARAMETER_UNKONWN' => array('code' => 1102, 'name' => array('en' => 'Parameter error', 'zh-CN' => '未知参数')),
        //参数校验失败：参数不能为空
        'ERROR_PARAMETER_NULL' => array('code' => 1103, 'name' => array('en' => 'Parameter error', 'zh-CN' => '参数不能为空')),
        //参数校验失败：参数长度限制
        'ERROR_PARAMETER_LENGTH' => array('code' => 1104, 'name' => array('en' => 'Parameter error', 'zh-CN' => '参数长度限制')),
        //参数校验失败：特定参数出现未预期的值
        'ERROR_PARAMETER_VLAUE' => array('code' => 1105, 'name' => array('en' => 'Parameter error', 'zh-CN' => '参数值不正确')),
        //参数校验失败：邮箱格式有误
        'ERROR_PARAMETER_VLAUE_EMAIL' => array('code' => 1106, 'name' => array('en' => 'The email format error', 'zh-CN' => '邮箱格式有误')),
        //参数校验失败：手机号码格式有误
        'ERROR_PARAMETER_VLAUE_PHONE' => array('code' => 1107, 'name' => array('en' => 'The phone number format error', 'zh-CN' => '手机号码格式有误')),
        //参数校验失败：
        'ERROR_PARAMETER_VLAUE_TOKEN' => array('code' => 1108, 'name' => array('en' => 'Parameter error', 'zh-CN' => '参数tn校验失败')),
        //访问过于频繁：
        'ERROR_LIMIT_TIMES' => array('code' => 1109, 'name' => array('en' => 'Access restricted', 'zh-CN' => '访问过于频繁')),
        
        //获取验证码失败
        'ERROR_MSMCODE_GET' => array('code' => 1110, 'name' => array('en' => 'Failure', 'zh-CN' => '获取验证码失败')),
        //今日获取验证码受限
        'ERROR_MSMCODE_LIMIT' => array('code' => 1111, 'name' => array('en' => 'Failure', 'zh-CN' => '获取验证码次数过多，请稍候再试')),
        //敏感词
        'ERROR_STOPWORD_LIMIT' => array('code' => 1120, 'name' => array('en' => 'Failure', 'zh-CN' => '你输入的内容包含敏感词请重新输入')),
        //2000-2099 个人账户 
        //用户账号：账号登录失败
        'ERROR_USER_LOGIN' => array('code' => 2000, 'name' => array('en' => 'Login error', 'zh-CN' => '账号登录失败')),
        //用户账号：账号未登录
        'ERROR_USER_UNLOGIN' => array('code' => 2001, 'name' => array('en' => 'Login error', 'zh-CN' => '账号未登录')),
        //用户账号：账号过期,请重新登录
        'ERROR_USER_TOKEN' => array('code' => 2002, 'name' => array('en' => 'Account expired', 'zh-CN' => '账号过期,请重新登录')),
        //用户账号：账号注册失败
        'ERROR_USER_REGISTER' => array('code' => 2003, 'name' => array('en' => 'registration failed', 'zh-CN' => '账号注册失败')),
        //用户账号：账号未注册
        'ERROR_USER_UNREGISTER' => array('code' => 2004, 'name' => array('en' => 'Account not registered', 'zh-CN' => '账号未注册')),
        //用户账号：账号已注册
        'ERROR_USER_ALREADY_REGISTER' => array('code' => 2005, 'name' => array('en' => 'Account has been registered', 'zh-CN' => '账号已注册')),
        //用户账号：已被绑定账号
        'ERROR_USER_ALREADY_BIND' => array('code' => 2006, 'name' => array('en' => 'Account has been bound', 'zh-CN' => '已被绑定账号')),
        //用户账号：未绑定账号
        'ERROR_USER_UNBIND' => array('code' => 2007, 'name' => array('en' => "Account hasn't been bound", 'zh-CN' => '未绑定账号')),
        //用户账号：绑定失败
        'ERROR_USER_BIND' => array('code' => 2008, 'name' => array('en' => 'Failed', 'zh-CN' => '绑定失败')),
        //用户账号：解绑失败
        'ERROR_USER_DELETE_BIND' => array('code' => 2009, 'name' => array('en' => 'Failed', 'zh-CN' => '解绑失败')),
        //用户账号：账号被锁定
        'ERROR_USER_LOCKED' => array('code' => 2010, 'name' => array('en' => 'Account is locked', 'zh-CN' => '账号被锁定')),
        //用户账号：账号被禁用
        'ERROR_USER_FORBIDDEN' => array('code' => 2011, 'name' => array('en' => 'Account is disabled', 'zh-CN' => '账号被禁用')),
        //用户账号：获取用户信息失败
        'ERROR_USER_GETINFO' => array('code' => 2012, 'name' => array('en' => 'Failed', 'zh-CN' => '获取失败')),
        //用户账号：更新用户信息失败
        'ERROR_USER_UPDATEINFO' => array('code' => 2013, 'name' => array('en' => 'Failed', 'zh-CN' => '更新失败')),
        //用户账号：用户权限不足
        'ERROR_USER_PERMISSION' => array('code' => 2014, 'name' => array('en' => 'Insufficient permission', 'zh-CN' => '用户权限不足')),
        //用户账号：密码有误
        'ERROR_USER_PWD' => array('code' => 2015, 'name' => array('en' => 'Wrong password', 'zh-CN' => '密码有误')),
        //用户账号：修改密码失败
        'ERROR_USER_PWDUPDATE' => array('code' => 2016, 'name' => array('en' => 'Failed', 'zh-CN' => '修改密码失败')),
        //用户账号：找回密码失败
        'ERROR_USER_PWD_SEARCH' => array('code' => 2017, 'name' => array('en' => 'Failed', 'zh-CN' => '找回密码失败')),
        //2000-2099 他人账户 
        //他人账户：不在线
        'ERROR_OTHERUSER_UNLINE' => array('code' => 2100, 'name' => array('en' => 'User not online', 'zh-CN' => '对方不在线')),
        //他人账户：获取失败
        'ERROR_OTHERUSER_GET' => array('code' => 2101, 'name' => array('en' => 'Failed', 'zh-CN' => '获取信息失败')),
        //他人账户：加好友失败
        'ERROR_OTHERUSER_ADDFRIEND' => array('code' => 2102, 'name' => array('en' => 'Add failed', 'zh-CN' => '加好友失败')),
        //他人账户：删除好友失败
        'ERROR_OTHERUSER_DELETEFRIEND' => array('code' => 2103, 'name' => array('en' => 'Failed to delete', 'zh-CN' => '删除失败')),
        //他人账户：关注失败
        'ERROR_OTHERUSER_ADDATTENTION' => array('code' => 2104, 'name' => array('en' => 'Failed', 'zh-CN' => '关注失败')),
        //他人账户：取消关注失败
        'ERROR_OTHERUSER_DELETEATTENTION' => array('code' => 2105, 'name' => array('en' => 'Failed', 'zh-CN' => '取消关注失败')),
        //他人账户：拉黑
        'ERROR_OTHERUSER_ADDBLACK' => array('code' => 2106, 'name' => array('en' => 'Failed', 'zh-CN' => '拉黑失败')),
        //他人账户：点赞主页
        'ERROR_OTHERUSER_PRAISE' => array('code' => 2107, 'name' => array('en' => 'Failed', 'zh-CN' => '点赞失败')),
        //他人账户：取消点赞主页
        'ERROR_OTHERUSER_UNPRAISE' => array('code' => 2108, 'name' => array('en' => 'Failed', 'zh-CN' => '取消点赞失败')),
        //3000-3999 （通常：每个实体的 增、删、改、查、获取列表 对应 01234）
        //评论：评论失败
        'ERROR_COMMENT_ADD' => array('code' => 3000, 'name' => array('en' => 'Comment failed', 'zh-CN' => '评论失败')),
        //评论：删除评论失败
        'ERROR_COMMENT_DELETE' => array('code' => 3001, 'name' => array('en' => 'Failed to delete', 'zh-CN' => '删除评论失败')),
        //评论：修改评论失败
        'ERROR_COMMENT_UPDATE' => array('code' => 3002, 'name' => array('en' => 'Failed to edit', 'zh-CN' => '修改评论失败')),
        //评论：获取评论失败,评论不存在
        'ERROR_COMMENT_GET' => array('code' => 3003, 'name' => array('en' => 'Failed', 'zh-CN' => '获取评论失败')),
        //评论：获取评论列表失败
        'ERROR_COMMENT_GETLIST' => array('code' => 3004, 'name' => array('en' => 'Failed', 'zh-CN' => '获取评论列表失败')),
        //点赞：点赞失败
        'ERROR_PRASIE_ADD' => array('code' => 3010, 'name' => array('en' => 'Failed', 'zh-CN' => '点赞失败')),
        //点赞：取消点赞
        'ERROR_PRASIE_DELETE' => array('code' => 3011, 'name' => array('en' => 'Failed', 'zh-CN' => '取消点赞失败')),
        //点赞：修改 
        //点赞：获取点赞失败
        'ERROR_PRASIE_GET' => array('code' => 3013, 'name' => array('en' => 'Failed', 'zh-CN' => '获取点赞失败')),
        //评论：获取评论列表失败
        'ERROR_PRASIE_GETLIST' => array('code' => 3014, 'name' => array('en' => 'Failed', 'zh-CN' => '获取点赞列表失败')),
        //收藏：收藏
        'ERROR_FAVORITE_ADD' => array('code' => 3020, 'name' => array('en' => 'Failed', 'zh-CN' => '收藏失败')),
        //收藏：取消收藏
        'ERROR_FAVORITE_DELETE' => array('code' => 3021, 'name' => array('en' => 'Failed', 'zh-CN' => '取消收藏失败')),
        //收藏：修改 
        //收藏：获取收藏失败
        'ERROR_FAVORITE_GET' => array('code' => 3023, 'name' => array('en' => 'Failed', 'zh-CN' => '获取收藏失败')),
        //收藏：获取收藏列表失败
        'ERROR_FAVORITE_GETLIST' => array('code' => 3024, 'name' => array('en' => 'Failed', 'zh-CN' => '获取收藏列表失败')),
        //通用：获取失败
        'ERROR_SOME_ADD' => array('code' => 3990, 'name' => array('en' => 'Failed', 'zh-CN' => '添加失败')),
        // 取消收藏
        'ERROR_SOME_DELETE' => array('code' => 3991, 'name' => array('en' => 'Failed', 'zh-CN' => '删除失败')),
        // 修改 
        'ERROR_SOME_UPDATE' => array('code' => 3992, 'name' => array('en' => 'Failed', 'zh-CN' => '更新失败')),
        // 获取失败
        'ERROR_SOME_GET' => array('code' => 3993, 'name' => array('en' => 'Failed', 'zh-CN' => '获取失败')),
        // 获取列表失败
        'ERROR_SOME_GETLIST' => array('code' => 3994, 'name' => array('en' => 'Failed', 'zh-CN' => '获取列表失败')),
        // 获取列表失败
        'ERROR_ACCUSE_ADD' => array('code' => 3995, 'name' => array('en' => 'Failed', 'zh-CN' => '举报错误')),
        // 验证码有误
        'ERROR_MSMCODE_ERROR' => array('code' => 3996, 'name' => array('en' => 'Failed', 'zh-CN' => '验证码有误')),
        // 超过设备上限
        'ERROR_DEVICE_LIMIT' => array('code' => 3997, 'name' => array('en' => 'Failed', 'zh-CN' => '超过设备上限')),
        // 登出失败
        'ERROR_LOGOUT' => array('code' => 3998, 'name' => array('en' => 'Failed', 'zh-CN' => '登出失败')),
        // 发布内容失败
        'ERROR_CONTENT_ADD' => array('code' => 3999, 'name' => array('en' => 'Failed', 'zh-CN' => '发布内容失败')),
        // 扫码未成功
        'ERROR_SCAN' => array('code' => 4000, 'name' => array('en' => 'Failed', 'zh-CN' => '未扫码或已登录')),
        // 二维码错误
        'ERROR_QRCODE' => array('code' => 4001, 'name' => array('en' => 'Failed', 'zh-CN' => '二维码错误')),
        // 二维码失效重新获取
        'ERROR_QRCODE_INVALID' => array('code' => 4002, 'name' => array('en' => 'Failed', 'zh-CN' => '二维码失效,重新获取')),
        // 获取关于
        'ERROR_ABOUT' => array('code' => 4003, 'name' => array('en' => 'Failed', 'zh-CN' => '获取关于失败')),
    );
    //返回值的类型校验
    public $returnDataPerType = array(
        
        'userType'=>'INT',
        'isFollow'=>'INT',
        'status'=>'INT',
        'userType'=>'INT',
        'videoTime'=>'INT',
        'startTime'=>'INT',
        'releaseTime'=>'INT',
        'startTime'=>'INT',
        'categoryId'=>'INT',
        'mustUpdate'=>'INT',
       
        
        
        //STRING
        'userId' => 'STRING',
        'programId' => 'STRING',
        'topicId' => 'STRING',
        'contentId' => 'STRING',
        'nickname' => 'STRING',
        'useIcon' => 'STRING',
        'recommendId' => 'STRING',
        'userIcon' => 'STRING',
        'commentId' => 'STRING',
        'replayId' => 'STRING',
        
        'title' => 'STRING',  
        'keywords' => 'STRING',
        'introduction' => 'STRING',
        'img' => 'STRING',
        
        'version' => 'STRING',
        'description' => 'STRING',
        'url' => 'STRING',
        
        'programName' => 'STRING',
        'programUrl' => 'STRING',  
        'topicName' => 'STRING',
        'userName' => 'STRING',
        'userImg' => 'STRING',
        'content' => 'STRING',
        
        //OBEJCT
//        'organizationObject' => 'OBEJCT',
        
        //ARRAY
//        'items' => 'ARRAY',
                
    );

    public function __construct($request) {
        $this->request = $request;
    }

    /*     *
     * @description :返回正确信息
     * @param: code，message
     * @return: json
     */

    public function returnOk($OK, $data = 'E', $paging = 'E', $cacheKey = '') {
        GLOBAL $cache;
//        $par = $this->request->all();
//        $action = trim(strrchr($this->request->route()[1]['uses'], '@'), '@');
//        Log::info($action.'Ok -json:' . json_encode($par));
        /*         * ************************ */
//        $this->debugQueryLog();
//		Log::info(var_export($queries, TRUE));
//		Log::info('SUMTIME__SQL'.$countTime);
        /*         * ************************ */

//        Log::info('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
        $returnInfo = array();
        $returnInfo['statusCode'] = $OK['code'];
        $returnInfo['message'] = $OK['name'][$this->RETURN_LANGUE];
        $returnInfo['timestamp'] = time();
        $returnStr = '';
        if ($data === 'E' && $paging === 'E') {
            $returnStr = json_encode($returnInfo, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
            if($cache){ // 
                //存数据
                $cache->cacheValue = $returnStr;
                $cache->HandleCache();
            }
            return $returnStr;
        }
        $data = $this->rectifyReturnDataPerType($data);
        if ($paging === 'E') {
            $returnInfo['data'] = $data;
            $returnStr = json_encode($returnInfo, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
            if($cache){ // 
                //存数据
                $cache->cacheValue = $returnStr;
                $cache->HandleCache();
            }
            return $returnStr;
        }
        if (isset($paging['page'])) {
            $returnInfo['page'] = (int) $paging['page'];
        }
        if (isset($paging['size'])) {
            $returnInfo['size'] = (int) $paging['size'];
        }
        if (isset($paging['count'])) {
            $returnInfo['count'] = (int) $paging['count'];
        }
        //总数存缓存
        $returnInfo['data'] = $data;
        $returnStr = json_encode($returnInfo, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        if($cache){ // 
            //存数据
            $cache->cacheValue = $returnStr;
            $cache->HandleCache();
        }
        return $returnStr;
    }

    /*     *
     * @description :返回错误信息
     * @param: code，message
     * @return: json
     */

    public function returnError($ERROR, $message = '') {
//        $this->debugQueryLog();
        GLOBAL $cache;
        $returnInfo = array();
        $returnInfo['statusCode'] = $ERROR['code'];
        $returnInfo['message'] = $ERROR['name'][$this->RETURN_LANGUE] ? $ERROR['name'][$this->RETURN_LANGUE] : 'Failure';
        if ($message && isset($message[$this->RETURN_LANGUE]) && $message[$this->RETURN_LANGUE]) {
            $returnInfo['message'] = $message[$this->RETURN_LANGUE];
        }
        $returnInfo['timestamp'] = time();
        $par = $this->request->all();
        $action = trim(strrchr($this->request->route()[1]['uses'], '@'), '@');
        Log::info($action .' EPG_ID ='. env('EPG_ID').' , USER_PRE ='. env('USER_PRE'). ',Error:' . $returnInfo['statusCode'] . ':' . $returnInfo['message']);
        Log::info('json:' . json_encode($par));
        $returnStr = json_encode($returnInfo, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
         if($cache){ // 
            //存数据
            $cache->cacheValue = $returnStr;
            $cache->HandleCache();
        }
        return $returnStr;
    }

    /*     *
     * @description :纠正
     * @param: code，message
     * @return: json
     */

    public function rectifyReturnDataPerType($object) {
        $object = json_decode(json_encode($object), true);
        if (is_array($object) || is_object($object)) {
            foreach ($object as $key => $value) {
                if (isset($this->returnDataPerType[$key])) {
                    switch ($this->returnDataPerType[$key]) {
                        case 'INT':
                            if (!is_numeric($value)) {
                                $value = 0;
                            }
                            $object[$key] = (int) $value;
                            break;
                        case 'OBEJCT':
                            if (!$value || !is_array($value)) {
                                $object[$key] = (Object) NULL;
                            } else {
                                $object[$key] = $this->rectifyReturnDataPerType($value);
                            }
                            break;
                        case 'ARRAY':
                            if (!$value || !is_array($value)) {
                                $object[$key] = array();
                            } else {
                                $object[$key] = $this->rectifyReturnDataPerType($value);
                            }
                            break;
                        case 'STRING':
                            $object[$key] = (string) $value; 
                            if ($key == 'contentId' || $key == 'userId' || $key == 'programId' || $key == 'topicId' || $key == 'recommendId' || $key == 'commentId' || $key == 'replayId') {
                                $object[$key] = with(new CommonUtils($this->request))->getUuid($value);
                            }
                            if ($key == 'token') {
                                $action = trim(strrchr($this->request->route()[1]['uses'], '@'), '@');
                                if ($action !== 'login') {
                                    $object[$key] = 'tn' . time() . rand(10000, 99999);
                                }
                            }
                            break;
                        default :
                            break;
                    }
                } else if (is_array($value) || is_object($value)) {
                    $object[$key] = $this->rectifyReturnDataPerType($value);
                } else if ($object[$key] === NULL) {
                    $object[$key] = '';
                }
            }
        }
        return $object;
    }
    
    
    
}
